<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j page-payment">
    <div class="content">
      <div class="step-box">
        <div class="left">
          <span class="img" />
          <span class="text">{{ $t('payment.orderPayment') }}</span>
        </div>
        <div class="steps">
          <div class="item">
            <div class="number">
              step 01.
            </div>
            <div class="text">
              {{ $t('payment.selectProductToBuy') }}
            </div>
          </div>
          <div class="item">
            <div class="number">
              step 02.
            </div>
            <div class="text">
              {{ $t('payment.confirmOrderInformation') }}
            </div>
          </div>
          <div class="item active">
            <div class="number">
              step 03.
            </div>
            <div class="text">
              {{ $t('payment.payToCompleteTheOrder') }}
            </div>
          </div>
        </div>
      </div>
      <div class="payment-con">
        <div class="pay-box">
          <div class="pay-info">
            <div class="tag success" />
            <div class="item">
              <div class="tit">
                {{ $t('payment.orderSubmittedSuccessfully') }}！
              </div>
              <div class="total-pay">
                {{ $t('payment.totalPayable') }}：
                <span class="price">
                  <span v-if="payOrderInfo.totalFee">￥{{ payOrderInfo.totalFee }}</span>
                  <span v-if="payOrderInfo.totalFee &&payOrderInfo.totalScore">+</span>
                  <span v-if="payOrderInfo.totalScore">{{ payOrderInfo.totalScore }}{{ $t('payment.points') }}</span>
                </span>
              </div>
            </div>
            <div class="item">
              <div
                v-if="isOverTime && $t('language') === 'zh_CN' "
                class="time"
              >
                请在
                <span class="warning">{{ min }} : {{ sec }}</span>内付款，否则交易会被取消。
              </div>
              <div
                v-if="isOverTime && $t('language') !== 'zh_CN'"
                class="time"
              >
                please pay within
                <span class="warning">{{ min }} : {{ sec }}</span>，otherwise the transaction will be cancelled。
              </div>
              <div
                v-if="!isOverTime"
                class="rest-time"
              >
                {{ $t('payment.orderHasExpired') }}
              </div>
              <div
                class="order-det"
                @click="showOrderInfo = !showOrderInfo"
              >
                {{ $t('payment.orderDetails') }}
              </div>
            </div>
          </div>
          <div
            v-if="showOrderInfo"
            class="order-info"
          >
            <div
              v-if="mold !==1 "
              class="text"
            >
              <div v-if="payOrderInfo.receiver||payOrderInfo.mobile||payOrderInfo.userAddr">
                <div
                  class="label"
                  :style="$t('language') ==='en'?'width: 140px':'width:  70px'"
                >
                  {{ $t('payment.receiptInformation') }}：
                </div>
                <div class="con">
                  {{ payOrderInfo.receiver }} {{ payOrderInfo.mobile }}
                </div>
                <div class="con">
                  {{ payOrderInfo.userAddr }}
                </div>
              </div>
            </div>
            <div class="text">
              <div
                class="label"
                :style="$t('language') ==='en'?'width: 140px':'width: 70px'"
              >
                {{ $t('payment.productName') }}：
              </div>
              <div class="con con-items">
                <div
                  v-for="item in payOrderInfo.prodNameList"
                  :key="item"
                  class="item"
                >
                  {{ item }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="section-payment">
          <div
            v-if="payOrderInfo.totalFee>0"
            class="tit"
          >
            {{ $t('payment.selectPaymentMethod') }}
          </div>
          <div
            v-if="payOrderInfo.totalFee>0"
            class="con"
          >
            <div
              v-if="paySwitchInfo.aliPaySwitch"
              class="item"
              :class="{active: payType === PayTypeConstant.ALIPAY}"
              @click="payType = PayTypeConstant.ALIPAY"
            >
              <img
                src="@/assets/images/payment-aliPay.png"
                alt
              >
              <span class="payment-text">{{ $t('payment.aliPay') }}</span>
              <div v-rich="payHtml" />
            </div>
            <div
              v-if="paySwitchInfo.wxPaySwitch"
              class="item"
              :class="{active: payType === PayTypeConstant.WECHATPAY_SWEEP_CODE}"
              @click="payType = PayTypeConstant.WECHATPAY_SWEEP_CODE"
            >
              <img
                src="@/assets/images/payment-wechatPay.png"
                alt
              >
              <span class="payment-text">{{ $t('payment.wechatPay') }}</span>
            </div>
            <div
              v-if="paySwitchInfo.payPalSwitch && paySettlementType!==1"
              class="item paypal"
              :class="{active: payType === PayTypeConstant.PAYPAL}"
              @click="payType = PayTypeConstant.PAYPAL"
            >
              <img
                class="paypal-logo"
                src="@/assets/images/paypal.png"
                alt
              >
              <img
                class="paypal-text"
                src="@/assets/images/paypal-text.png"
                alt
              >
            </div>
            <div
              v-if="paySwitchInfo.balancePaySwitch"
              class="item paypal item-balance"
              :class="{active: payType === PayTypeConstant.BALANCEPAY}"
              @click="payType = PayTypeConstant.BALANCEPAY"
            >
              <img
                class="paypal-logo item-balance-img"
                src="@/assets/images/balancePay.png"
                alt
              >
              <div class="payment-text item-balance-div">
                {{ $t('payment.balancePay') }}<span class="item-balance-span">({{ $t('payment.availableBalance') }}：{{ currentBalance }})</span>
              </div>
            </div>
          </div>
          <a
            href="javascript:void(0)"
            :class="[isCanPay ? '' : 'no-pay', 'btn']"
            @click="toPay"
          >{{ $t('payment.payNow') }}</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { PayType } from '@/utils/constant'
import { checkPayWay } from '@/utils/index'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
const showOrderInfo = ref(false) // 是否显示订单详情
const payType = ref(PayType.ALIPAY)// 支付类型，默认支付宝
const PayTypeConstant = ref(PayType) // 支付类型常量
const router = useRouter()
const mold = ref(null)
let orderNumber = '' // 订单号
const paySettlementType = ref(null)
let allinpayMemberInfo = {}
onMounted(() => {
  paySettlementType.value = localStorage.getItem('bbcPaySettlementType') ? JSON.parse(localStorage.getItem('bbcPaySettlementType')).paySettlementType : 0
  if (paySettlementType.value === 1) {
    getAllinpayMember()
  }
  orderNumber = sessionStorage.getItem('bbcPay_orderNumber')
  mold.value = Number(sessionStorage.getItem('bbcPay_mold'))
  getOrderDetail()
  setDefaultPayType()
  getBalanceInfo()
  nextTick(() => {
    document.title = $t('payment.checkoutCounter')
  })
})
let timer = null // 倒计时变量
onUnmounted(() => {
  if (timer) { // 如果定时器在运行则关闭
    clearInterval(timer)
  }
})

/**
 * 设置默认支付类型
 */
const paySwitchInfo = ref('')
const setDefaultPayType = () => {
  http.get('/sys/config/info/getSysPaySwitch').then(({ data }) => {
    paySwitchInfo.value = data
    if (paySwitchInfo.value.aliPaySwitch) {
      return
    }
    if (paySwitchInfo.value.wxPaySwitch) {
      payType.value = PayType.WECHATPAY_SWEEP_CODE
      return
    }
    if (paySwitchInfo.value.balancePaySwitch) {
      payType.value = PayType.WECHATPAY_SWEEP_CODE
      return
    }
    if (paySwitchInfo.value.payPalSwitch) {
      payType.value = PayType.PAYPAL
    }
  })
}
// 请求支付订单详情
const payOrderInfo = ref({}) // 支付订单详情
const getOrderDetail = () => {
  http.get('/p/order/getOrderPayInfoByOrderNumber', {
    params: {
      orderNumbers: orderNumber
    }
  }).then(({ data }) => {
    payOrderInfo.value = data
    countTime()
  })
}

// 获取余额信息
const currentBalance = ref(0) // 余额
const getBalanceInfo = () => {
  http.get('/p/userBalance/getBalanceInfo').then(({ data }) => {
    currentBalance.value = data
  })
}

// 倒计时
const min = ref('00') // 分
const sec = ref('00') // 秒
const isCanPay = ref(true) // 是否能支付
const isOverTime = ref(true) // 能否支付的文字提示

const countTime = () => {
  // 获取当前时间
  const date = new Date()
  const now = date.getTime()

  // // 设置截止时间（）
  const end = new Date(payOrderInfo.value.endTime.toString().replace(/-/g, '/')).getTime()

  // 时间差
  const leftTime = end - now

  // 定义变量 d,h,m,s保存倒计时的时间
  if (leftTime >= 0) {
    // 分
    const m = Math.floor(leftTime / 1000 / 60 % 60)
    min.value = m < 10 ? '0' + m : m
    // 秒
    const s = Math.floor(leftTime / 1000 % 60)
    sec.value = s < 10 ? '0' + s : s
  } else {
    min.value = '00'
    sec.value = '00'
    isOverTime.value = false
    isCanPay.value = false
  }
  // 等于0的时候不调用
  if (Number(min.value) === 0 && Number(sec.value) === 0) {
    return
  }
  // 递归每秒调用countTime方法，显示动态时间效果,
  timer = setTimeout(countTime, 1000)
}

// 去支付
let isPayDuring = false
const payHtml = ref('') // 支付宝页面
const toPay = () => {
  if (paySettlementType.value) {
    // 开通了通联支付则需要判断是否实名认证与绑定手机号
    if (getTip(payType.value)) {
      return
    }
  }
  if (isPayDuring) {
    return
  }
  isPayDuring = true
  if (isCanPay.value && payOrderInfo.value.totalFee === 0 && payOrderInfo.value.totalScore) {
    // 纯积分
    http.post('/p/order/pay', {
      payType: PayType.SCOREPAY,
      orderNumbers: orderNumber,
      systemType: 1,
      allinPaySystemType: paySettlementType.value === 1 ? 2 : undefined
    }).then(() => {
      router.push({ path: '/user-center/uc-order' })
    }).finally(() => {
      isPayDuring = false
    })
    return
  }
  if (!checkPayWay(paySwitchInfo.value)) return
  if (isCanPay.value) {
    const type = payType.value
    if (type === PayType.ALIPAY) {
      http.post('/p/order/pay', {
        payType: type,
        orderNumbers: orderNumber,
        returnUrl: window.location.origin + '/user-center/uc-order',
        systemType: 1,
        allinPaySystemType: paySettlementType.value === 1 ? 2 : undefined
      }).then(({ data }) => {
        if (paySettlementType.value === 1) {
          // 通联支付下，支付宝支付改为扫码支付
          router.push({
            path: '/weixin-pay', query: { payType: type }
          })
          return
        }
        // 支付宝部分
        payHtml.value = data
        nextTick(() => {
          document.forms[0].submit()
        })
      }).finally(() => {
        isPayDuring = false
      })
    } else if (type === PayType.WECHATPAY_SWEEP_CODE) {
      // 微信部分
      isPayDuring = false
      router.push({
        path: '/weixin-pay', query: { payType: type }
      })
    } else if (type === PayType.PAYPAL) {
      // PayPal部分
      const loading = ElLoading.service({
        lock: true,
        text: $t('loading'),
        background: 'rgba(255, 255, 255, 0.8)'
      })
      http.post('/p/order/pay', {
        payType: type,
        orderNumbers: orderNumber,
        returnUrl: window.location.origin + '/user-center/uc-order',
        systemType: 1
      }).then(({ data }) => {
        window.location.href = data
        if (navigator.userAgent.indexOf('Safari') > 0) {
          setTimeout(() => {
            loading.close()
          }, 2000)
        }
      }).catch(() => {
        setTimeout(() => {
          loading.close()
        }, 1000)
      }).finally(() => {
        isPayDuring = false
      })
    } else if (type === PayType.BALANCEPAY) {
      // 余额部分
      if (parseFloat(payOrderInfo.value.totalFee) > parseFloat(currentBalance.value)) {
        ElMessage({
          message: $t('payment.balanceTip') + currentBalance.value,
          type: 'none',
          duration: 3000
        })
        isPayDuring = false
        return
      }
      const {
        protocol,
        host
      } = window.location

      if (paySettlementType.value === 1) {
        http.post('/p/order/pay', {
          payType: type,
          orderNumbers: orderNumber,
          returnUrl: `${protocol}//${host}` + '/user-center/uc-order',
          allinPaySystemType: paySettlementType.value === 1 ? 2 : undefined
        }).then(({ data }) => {
          const confirmData = {
            bizOrderNo: data.bizOrderNo,
            jumpUrl: `${protocol}//${host}/user-center/uc-order`,
            errorJumpUrl: `${protocol}//${host}/user-center/uc-order`,
            jumpPageType: 1
          }
          http.post('/p/allinpay/order/payConfirmByFrontPwd', confirmData).then(({ data }) => {
            nextTick(() => {
              location.href = data
            })
          })
        })
        return
      }
      ElMessageBox.confirm($t('myBalance.payTips'), $t('tips'), {
        distinguishCancelAndClose: true,
        confirmButtonText: $t('determine'),
        cancelButtonText: $t('cancel')
      }).then(() => {
        http.post('/p/order/pay', {
          payType: type,
          orderNumbers: orderNumber,
          returnUrl: window.location.origin + '/user-center/uc-order',
          systemType: 1
        }).then(() => {
          ElMessage({
            message: $t('payment.paymentSuccessful'),
            type: 'success',
            duration: 1000,
            onClose () {
              router.push({ path: '/user-center/uc-order' })
            }
          })
        }).finally(() => {
          isPayDuring = false
        })
      }).catch(() => {
        isPayDuring = false
      })
    }
  } else {
    isPayDuring = false
    return false
  }
}
// 获取通联支付用户信息
const getAllinpayMember = () => {
  http.get('/p/userExtension/getInfo').then(({ data }) => {
    allinpayMemberInfo = data
  })
}

// 获取是否完成实名/绑定手机号提示（判断是否实名认证与绑定手机号）
const getTip = (type) => {
  if (!allinpayMemberInfo) {
    ElMessage({
      message: $t('allinpay.loadingTip'),
      type: 'error',
      duration: 1000
    })
    return true
  }
  if (type === PayType.BALANCEPAY) {
    // 余额支付需要判断实名认证与绑定手机号
    let msg = ''
    if (!allinpayMemberInfo.allinpayRealNameSet) {
      msg += $t('allinpay.realNameTip1')
    }
    if (!allinpayMemberInfo.allinpayPhoneBind) {
      if (msg) {
        msg += $t('allinpay.bindPhone2')
      } else {
        msg += $t('allinpay.bindPhone')
      }
    }
    if (!allinpayMemberInfo.allinpayPayPwdSet) {
      if (msg) {
        msg += $t('allinpay.setPayPwd2')
      } else {
        msg += $t('allinpay.setPayPwd')
      }
    }
    if (msg) {
      ElMessage({
        message: $t('allinpay.tip1') + msg + $t('allinpay.tip2'),
        type: 'error',
        duration: 1000
      })
      return true
    }
  } else if (type === PayType.ALIPAY || type === PayType.WECHATPAY_SWEEP_CODE) {
    // 支付宝与微信支付需要判断是否为无感注册用户，或是否绑定手机号
    if (!allinpayMemberInfo.allinpayPayAcctBind && !allinpayMemberInfo.allinpayPhoneBind) {
      ElMessage({
        message: $t('allinpay.tip3'),
        type: 'error',
        duration: 1000
      })
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
@use './index.scss';
</style>
